using System.IO;
using UnityEngine;
using LitJson;
using System.Collections.Generic;
#if UNITY_IOS && !UNITY_EDITOR
using System.Runtime.InteropServices;
#endif

namespace CGF
{
    public class GetPhotoIOS : MonoBehaviour
    {
#if UNITY_IOS && !UNITY_EDITOR
        // 导入原生插件中的函数
        [DllImport("__Internal")]
        private static extern void _OpenPhotoPicker(int maxSelection);
#endif

        private CTask<string[]> task;

        // 单例模式（可选但推荐，用于接收回调）
        private static GetPhotoIOS _instance;
        public static GetPhotoIOS Instance
        {
            get
            {
                if (!_instance)
                {
                    _instance = GameObject.FindObjectOfType<GetPhotoIOS>();
                    if (!_instance)
                    {
                        GameObject go = new GameObject(nameof(GetPhotoIOS));
                        _instance = go.AddComponent<GetPhotoIOS>();
                        DontDestroyOnLoad(go);
                    }
                }
                return _instance;
            }
        }

        public async CTask<string[]> _GetPhotoFromAlbum(int maxSelection)
        {
            task = CTask<string[]>.Create();
#if UNITY_IOS && !UNITY_EDITOR
            _OpenPhotoPicker(maxSelection);
#endif
            return await task;
        }

        public byte[] _GetBytesByPath(string path)
        {
            if (File.Exists(path))
            {
                return File.ReadAllBytes(path);
            }
            else
            {
                Debug.LogError($"Image file not found at path: {path}");
                return null;
            }
        }
        
        // 用于接收原生回调的MonoBehaviour方法，使用public防止被混淆
        public void _OnPhotoPickedCallback(string json)
        {
            Debug.Log($"json: {json}");
            if (string.IsNullOrEmpty(json))
            {
                task.SetResult(null);
                return;
            }
            List<string> paths = new List<string>();
            JsonData jsonData = JsonMapper.ToObject(json);
            for (int i = 0; i < jsonData.Count; i++)
            {
                paths.Add(jsonData[i]["path"].ToString());
            }
            task.SetResult(paths.ToArray());
        }
    }
}
